<?php
/**
 * Message Viewer
 * 
 * 
 */
use Fox\Behaviors;
use Fox\Ressources\Script;
use Fox\Html\Html;
use Fox\Generator;
use Fox\Html\Screen;
use Fox\Html\TextArea;
use Orx\Mailer\MailBox\Message\Reader\Classic;
use Orx\Mailer\MailBox\Message;
$xview = Xview::instance();
if(!$xview->ajax()) {
//	return;
}
$messageid = $xview->val('messageid');
$area = $xview->val('area');
$status = $xview->val('status');
$mode  = $xview->val('mode',false);
$summary  = $xview->val('summary',false);
$container = $xview->val('container','contentCol');

try {
	$message = Fox\Dao::load(Message::className(), $messageid);
	$title = Fox\Utilities\DateTimes::toFullString($message->received_date).' '.$message->email;
	if($message->status == Message::STATUS_UNREAD) {
		$message->status = Message::STATUS_READ;
		$message->prepareUpdate(Message::CHANGE_DEFAULT);
		$message->update();
	}
} catch(Fox\Object\Exception\NotExist $e) {
	return;
} catch(Fox\Object\Exception\Save $e) {
	
}

$behaviorGoBack = new Behaviors(Behaviors::action(
	Generator::url('messages','list',null,array(
		'mode' => $mode,
		'area' => $area,
		'status' => $status,
		'container' => $container,
		'summary' => $summary,
		'reference' => $xview->val('reference'))),
	false,
	null,
	null,
	false,
	'POST',
	null,
	null,
	$container,
	false
));
$style = 'position: relative;height:35px;top:0';
if($container == 'contentCol') {
	if(!$mode) {
		$style = 'position: absolute;';
	}
} 
// Back Button
$backButton = '
<div class="left-params" style="'.$style.'">
	<a title="'.Msg(Orx\Mailer\Messages::BUNDLE,Orx\Mailer\Messages::BACK_TO_MESSAGES_LIST).'" 
		class="btn  inverse '.$behaviorGoBack->serialize($message,'back').'" id="act-back" href="#" style="margin-left: -2px;" 
		data-uri="?mod=messages&act=list&area='.$area.'&status='.$status.'"
		data-position="bottom" >
		<i class="icon-arrow-left"></i>
		</a>
</div>';
$html = $backButton;
// ------------------- Messages ------------------------//

// 1. Find First Conversation Message
$parent = Message::findTopParent($message);

// 2. Find All Children starting from the oldest parent
$childrens = Message::buildChildrenArray($parent);
$hasanswer = false;
$htmlParts = array();
// 3. Walkthrough the array to display all the messages
foreach($childrens as $child) {
	if($child->status == Message::STATUS_DRAFT) {
		$hasanswer = true;
		$htmlParts[$child->messageid] = new \Orx\Mailer\MailBox\Message\Editor\Classic($child);
	} else {
		$htmlParts[$child->messageid] = new \Orx\Mailer\MailBox\Message\Reader\Classic($child);
		$htmlParts[$child->messageid]
				->labelGenerator(\Hive\Ressource::labelGenerator())
				->titleGenerator(\Hive\Ressource::titleGenerator());
		if(empty($lastMessageId)) {
			$htmlParts[$child->messageid]->withTitle = true;
		}
		$lastMessage = $child;
		$lastMessageId = $child->messageid;
	}
}
$lastMessageId = (empty($lastMessageId)) ? $messageid : $lastMessageId;
$htmlParts[$lastMessageId]->collapsed = false;
foreach($htmlParts as $part) {
	$html .= $part->render();
}

$lastConversationId = $lastMessageId;
$lastConversationTarget = $message->email;
// Mark as read
$hideAnswer = ($hasanswer) ? ' hide' : null;

$userProfilePicture = User::current()->profilePictureUrl(true);
if(!$mode) {
$html .= '<div class="message-answer'.$hideAnswer.'" id="message-answer-band">
					<img src="'.$userProfilePicture.'">
					<div class="answer-box">
						<p>
						'.Msg(Hive::BUNDLE,Hive::MESSAGE_ANSWER_OR_FORWARD).'
						</p>
					</div>
			</div>';
} else {
	$html .= '<br><div class="message-answer'.$hideAnswer.'" id="message-answer-band"><p></p></div>';
}
// Message Answer

// 1. First check if there is a draf answer 
if(!$hasanswer && !$mode) {
	if(empty($lastMessage)) {
		$lastMessage = $message;
	}
	$answerMessage = new Orx\Mailer\MailBox\Message();
	$answerContent = '<br>
						<blockquote class="hive-blockquote" data-messageid="'.$lastMessageId.'" style="padding: 0 0 0 15px;margin: 0 0 20px;border-left: 5px solid #eeeeee;">
							<p style="height:0;line-height:0;overflow:hidden;display:none">###'.$lastMessageId.'###</p>
							<p>'.$title.'</p>
							<p style="margin-bottom:0;font-size:17.5px;font-weight: 300;line-height: 1.25;">'.$lastMessage->content().'</p>
						</blockquote>';
	$answerMessage->setFields(array(
		'email' => $lastMessage->mailbox()->email,
		'subject' => $message->subject,
		'content' => strip_tags($answerContent),
		'content_html' => $answerContent,
		'parentid' => $message->getId()
	));
	$receiver = new  \Orx\Mailer\MailBox\Message\Receiver();
	$receiver->setFields(array(
		'name' => $lastMessage->name,
		'reference' => $lastMessage->reference,
		'reference_class_id' => 1,
		'email' => $lastMessage->email,
	));
	$answerMessage->addToReceivers($receiver);
	$editor = new \Orx\Mailer\MailBox\Message\Editor\Classic($answerMessage);
	$editor->hidden();
	$editor->renderingMode(\Orx\Mailer\MailBox\Message\Editor\Classic::RENDERING_MODE_ANSWER);
	$html .= $editor->render();
}

$sender = $message->mailbox()->email;
$boxid = $message->mailbox()->boxid;
$receivers = $lastConversationTarget;

$screen = new Screen('answer-screen','send',null,true,Generator::ajaxReload('contentCol'));
if($screen->submitted()) {
	$editor = new \Orx\Mailer\MailBox\Message\Editor\Classic(new Message());
	$editor->parsePostResult();
	exit;
}

\Fox\Ressources::instance()->register(new Script(_ASSETS_.'js/mailbox.js'));
$html .= \Fox\Ressources::instance()->dump();

// 
$sourceBehavior = new Behaviors(Behaviors::source(Generator::url('messages','viewer',null,$_GET)));
$scrolling = ($mode) ? 'container-scroll' : '';
$html= '<div id="viewer-container" class="'.$scrolling.' '.$sourceBehavior->serialize($message,'reload').'">'.$html.'</div>';

if($xview->ajax()) {
	echo $html;
} else {
	return $html;
}